<template>
    <div class="homeContain">
        <div class="wrong-book-page">
            <HomeTop style="position: sticky;top: 0;z-index: 10;" />
            <!-- 顶部工具栏 -->
            <header class="toolbar">
                <button @click="selectButton('all')" :class="{ selected: selectedButton === 'all' }">
                    全部
                </button>
                <button @click="selectButton('week')" :class="{ selected: selectedButton === 'week' }">
                    近一周
                </button>
                <button @click="selectButton('month')" :class="{ selected: selectedButton === 'month' }">
                    近一个月
                </button>
                <button @click="selectButton('collect')" :class="{ selected: selectedButton === 'collect' }"
                    style="background-color: #4CAF50;">
                    收藏错题集
                </button>
            </header>

            <div class="content-container">
                <!-- 主内容区 -->
                <main class="main-content">
                    <div v-if="questions.length === 0" class="no-questions-message">
                        <p>你做得很好，继续加油，你以解决所有错题了！</p>
                    </div>
                    <div v-else>
                        <div v-for="(question, index) in questions" :key="index" class="question-item">
                            <div class="question-detail">
                                <p class="question-title">{{ question.title }}</p>
                                <ul class="question-options">
                                    <li v-for="(option, idx) in question.options" :key="idx">
                                        {{ String.fromCharCode(65 + idx) }}. {{ option }}
                                    </li>
                                </ul>
                                <p class="correct-answer">正确答案：{{ String.fromCharCode(65 + question.correctAnswer) }}
                                </p>
                            </div>
                            <div class="question-actions">
                                <button
                                    :style="{ backgroundColor: question.isCollectUser ? 'rgb(100, 200, 100)' : 'rgb(235, 185, 34)' }"
                                    @click="collectQuestion(index)">
                                    {{ question.isCollectUser ? '已收藏' : '收藏错题' }}

                                </button>

                                <button @click="writeNote(index)">制作笔记</button>
                                <button style="background-color: #ea3323;" @click="deleteQuestion(index)">移除错题集</button>
                            </div>
                        </div>
                    </div>
                </main>


                <!-- 侧边栏 -->
                <aside class="sidebar">
                    <h3 class="sidebar-title">错题统计</h3>
                    <div class="statistics-container">
                        <div class="stat-item">
                            <span class="stat-title">总错题数</span>
                            <span class="stat-value">{{ statistics.total }}</span>
                        </div>
                        <div class="stat-item">
                            <span class="stat-title">近一周错题数</span>
                            <span class="stat-value">{{ statistics.lastWeekNum }}</span>
                        </div>
                        <div class="stat-item">
                            <span class="stat-title">近一月错题数</span>
                            <span class="stat-value">{{ statistics.lastMonthNum }}</span>
                        </div>
                        <div class="stat-item">
                            <span class="stat-title">花卉相关错题数</span>
                            <span class="stat-value">{{ statistics.flowersRelatedNum }}</span>
                        </div>
                        <div class="stat-item">
                            <span class="stat-title">盆景相关错题数</span>
                            <span class="stat-value">{{ statistics.bonsaiRelatedNum }}</span>
                        </div>
                        <div class="stat-item">
                            <span class="stat-title">多肉植物相关错题数</span>
                            <span class="stat-value">{{ statistics.succulentsRelatedNum }}</span>
                        </div>
                        <div class="stat-item">
                            <span class="stat-title">树相关错题数</span>
                            <span class="stat-value">{{ statistics.treesRelatedNum }}</span>
                        </div>
                        <div class="stat-item">
                            <span class="stat-title">收藏的错题数</span>
                            <span class="stat-value">{{ statistics.collected }}</span>
                        </div>
                        <div class="stat-item">
                            <span class="stat-title">已写笔记</span>
                            <span class="stat-value">{{ statistics.noted }}</span>
                        </div>
                    </div>
                </aside>
            </div>

            <!-- 底部工具栏 -->
            <footer class="bottom-toolbar">
                <button @click="exportQuestions">导出错题</button>
                <button @click="randomPractice">随机练习</button>
            </footer>
        </div>
    </div>
</template>
<script>
import html2pdf from 'html2pdf.js';
import request from '@/utils/request';
import { newPage } from '@/utils/commonFunction'
import HomeTop from '../components/HomeTop.vue'
export default {
    components: {
        HomeTop,
    },
    data() {
        return {
            selectedButton: 'all',
            currentPage: 1,
            currentType: 1,
            questions: [
            ],
            statistics: {
                total: 2,
                lastWeekNum: 1,
                lastMonthNum: 2,
                flowersRelatedNum: 0,
                bonsaiRelatedNum: 0,
                succulentsRelatedNum: 0,
                treesRelatedNum: 0,
                collected: 0,
                noted: 0,
            },
        };
    },
    created() {
        this.filterByAll();
        this.getStatistics();
        window.addEventListener('scroll', this.handleScroll); // 添加滚动事件监听
    },
    beforeDestroy() {
        window.removeEventListener('scroll', this.handleScroll); // 移除滚动事件监听
    },
    methods: {
        newPage,
        selectButton(button) {
            this.selectedButton = button;
            this.currentPage = 1;
            this.questions = [];
            // 根据按钮选择过滤数据
            if (button === 'all') {
                this.filterByAll(1);
            } else if (button === 'week') {
                this.filterByWeek(1);
            } else if (button === 'month') {
                this.filterByMonth(1);
            } else if (button === 'collect') {
                this.filterByCollect(1);
            }
        },
        handleScroll() {
            const scrollTop = window.scrollY || document.documentElement.scrollTop;
            const windowHeight = window.innerHeight;
            const documentHeight = document.documentElement.scrollHeight;

            // 判断是否滚动到底部
            if (scrollTop + windowHeight >= documentHeight - 10) { // 设置一个小偏差，避免触发不稳定
                if (this.currentType === 1) {
                    this.filterByAll(this.pageNum);
                } else if (this.currentType === 2) {
                    this.filterByWeek(this.pageNum);
                } else if (this.currentType === 3) {
                    this.filterByMonth(this.pageNum);
                } else if (this.currentType === 4) {
                    this.filterByCollect(this.pageNum);
                }
            }
        },
        // 获取错题数据
        getWrongQuestions(startTime, endTime, pageNum) {
            const userId = JSON.parse(localStorage.getItem('userInfo')).id;
            request.get(`/incorrectQuestions/user/${userId}`, {
                params: {
                    startTime: startTime,
                    endTime: endTime,
                    pageNum: this.currentPage
                }
            })
                .then(response => {
                    if (response.code === 200) {
                        // 转换后端数据为前端要求的格式
                        this.questions = [
                            ...this.questions,
                            ...response.data.map(item => ({
                                collectId: item.collectId,
                                correctAnswer: item.correctAnswer, // 正确答案索引
                                createdAt: item.createdAt,
                                id: item.id,
                                isCollectUser: item.isCollectUser,
                                options: JSON.parse(item.options), // 解析 options 字符串为数组
                                postId: item.postId,
                                questionId: item.questionId,
                                title: item.question, // 题目内容

                            }))];
                        if (response.data.length > 0) {
                            this.currentPage += 1;
                        }
                    } else {
                        console.error("查询失败:", response.msg);
                    }
                })
                .catch(error => {
                    console.error("获取题目数据失败", error);
                });
        },

        // 筛选全部
        filterByAll(pageNum) {
            this.currentType = 1;
            const startTime = ''; // 可以调整为合适的默认起始时间
            const endTime = ''; // 可以调整为合适的默认结束时间
            this.getWrongQuestions(startTime, endTime, pageNum);
        },

        // 筛选近一周
        filterByWeek(pageNum) {
            this.currentType = 2;
            const currentDate = new Date();
            const weekAgo = new Date(currentDate);
            weekAgo.setDate(currentDate.getDate() - 7); // 当前日期减去7天

            // 调整当前时间和一周前的时间，增加8小时，抵消时差
            currentDate.setHours(currentDate.getHours() + 8);
            weekAgo.setHours(weekAgo.getHours() + 8);

            const startTime = weekAgo.toISOString().slice(0, 19).replace("T", " "); // 格式化时间
            const endTime = currentDate.toISOString().slice(0, 19).replace("T", " "); // 格式化时间

            this.getWrongQuestions(startTime, endTime, pageNum);
        },


        // 筛选近一个月
        filterByMonth(pageNum) {
            this.currentType = 3;
            const currentDate = new Date();
            const monthAgo = new Date(currentDate);
            monthAgo.setMonth(currentDate.getMonth() - 1); // 当前日期减去1个月
            currentDate.setHours(currentDate.getHours() + 8);
            monthAgo.setHours(monthAgo.getHours() + 8);

            const startTime = monthAgo.toISOString().slice(0, 19).replace("T", " "); // 格式化时间
            const endTime = currentDate.toISOString().slice(0, 19).replace("T", " "); // 格式化时间

            this.getWrongQuestions(startTime, endTime, pageNum);
        },
        filterByCollect(pageNum) {
            this.currentType = 4;
            const userId = JSON.parse(localStorage.getItem('userInfo')).id;
            request.get(`/collectIncorrect/user/${userId}`, {
                params: {
                    pageNum: this.currentPage
                }
            })
                .then(response => {
                    if (response.code === 200) { 
                        // 转换后端数据为前端要求的格式
                        this.questions = [
                            ...this.questions,
                            ...response.data.map(item => ({
                                collectId: item.collectId,
                                correctAnswer: item.correctAnswer, // 正确答案索引
                                createdAt: item.createdAt,
                                id: item.id,
                                isCollectUser: item.isCollectUser,
                                options: JSON.parse(item.options), // 解析 options 字符串为数组
                                postId: item.postId,
                                questionId: item.questionId,
                                title: item.question, // 题目内容

                            }))];
                        if (response.data.length > 0) {
                            this.currentPage += 1;
                        }
                    }
                })
        },
        getStatistics() {
            const userId = JSON.parse(localStorage.getItem('userInfo')).id;
            request.get(`/incorrectQuestions/statistics/${userId}`).then(response => {
                if (response.code === 200) {
                    // 转换后端数据为前端要求的格式
                    this.statistics = response.data;
                } else {
                    console.error("查询失败:", response.msg);
                }
            });
        },
        collectQuestion(index) {
            const question = this.questions[index];
            if (!question.isCollectUser) {
                request.post('/collectIncorrect/add', {
                    incorrectQuestionId: this.questions[index].id, // 假设每个问题有唯一的 id
                    userId: JSON.parse(localStorage.getItem('userInfo')).id,
                })
                    .then(response => {
                        console.log("收藏成功", response);
                        this.questions[index].isCollectUser = true;
                        this.questions[index].collectId = response.data;
                    })
                    .catch(error => {
                        console.error("收藏失败", error);
                    })
            } else {
                request.delete(`/collectIncorrect/${question.collectId}`).then(response => {
                    console.log("取消收藏成功", response);
                    this.questions[index].isCollectUser = false;
                })
                    .catch(error => {
                        console.error("取消收藏失败", error);
                    })
            }
        },
        writeNote(index) {
            // 写笔记函数占位
            console.log(`写笔记: ${index}`);

            // 获取题目信息
            const questionTitle = this.questions[index].title;
            const options = this.questions[index].options;
            const correctAnswer = String.fromCharCode(65 + this.questions[index].correctAnswer);

            // 拼装笔记内容
            let noteContent = `
### 题目
${questionTitle}

${options.map((option, i) => `${String.fromCharCode(65 + i)}. ${option}`).join('\n')}

### 正确答案
${correctAnswer}


::: hljs-center

------分割线------

:::
`;

            // 保存到 sessionStorage
            sessionStorage.setItem('note', JSON.stringify({
                noteTitle: "", // 可以自行设置标题
                noteContent: noteContent,
                tags: "" // 可以自行设置标签
            }));

            // 跳转到笔记页面
            newPage('/note/write');
        },

        deleteQuestion(index) {
            request.delete(`/incorrectQuestions/${this.questions[index].id}`).then(response => {
                console.log("删除成功", response);
                this.questions.splice(index, 1);
            })
                .catch(error => {
                    console.error("删除失败", error);
                })
        },
        exportQuestions() {
            // 导出错题函数占位
            const element = document.getElementsByClassName('content-container')[0];
            html2pdf()
                .from(element)
                .save('output.pdf');
            console.log(element);
        },
        randomPractice() {
            sessionStorage.setItem('quizQuestions', JSON.stringify(this.questions));
            newPage('/exerciseMistakes')
        },
    },
};
</script>

<style scoped>
.homeContain {
    padding: 100px 100px 0 100px;
    background-image: url('@/assets/image/back.png');
}

.wrong-book-page {
    display: flex;
    flex-direction: column;
    background: white;
}

.toolbar {
    display: flex;
    justify-content: flex-start;
    padding: 10px;
    background-color: #f5f5f5a4;
    border-bottom: 1px solid #ddd;
}

.toolbar button {
    padding: 5px 10px;
    margin: 0 5px;
    background-color: #007bff;
    color: #fff;
    border: none;
    border-radius: 4px;
    cursor: pointer;
}

.content-container {
    display: flex;
    flex: 1;
}

.main-content {
    flex: 3;
    padding: 10px;
    overflow-y: auto;
}

.question-item {
    border: 1px solid #ddd;
    border-radius: 4px;
    padding: 10px;
    margin-bottom: 10px;
    background-color: #fff;
}

.question-title {
    font-weight: bold;
}

.question-options {
    list-style: none;
    padding: 0;
    margin: 5px 0;
}

.question-options li {
    margin: 3px 0;
}

.correct-answer {
    color: #28a745;
}

.question-actions button {
    margin-right: 5px;
    padding: 5px 10px;
    background-color: #007bff;
    color: #fff;
    border: none;
    border-radius: 4px;
    cursor: pointer;
}

.sidebar {
    flex: 1;
    padding: 10px;
    background-color: #f9f9f9;
    border-left: 1px solid #ddd;
}

.sidebar {
    background: #f9f9f9;
    border: 1px solid #ddd;
    border-radius: 8px;
    padding: 16px;
    max-width: 300px;
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
    font-family: Arial, sans-serif;
}

.sidebar-title {
    font-size: 1.5em;
    color: #333;
    text-align: center;
    margin-bottom: 16px;
}

.statistics-container {
    display: grid;
    grid-template-columns: 1fr;
    gap: 12px;
}

.stat-item {
    background: #fff;
    padding: 12px;
    border-radius: 6px;
    border: 1px solid #eee;
    display: flex;
    justify-content: space-between;
    align-items: center;
    transition: transform 0.2s;
}

.stat-item:hover {
    transform: translateY(-4px);
    box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}

.stat-title {
    font-size: 1em;
    color: #555;
}

.stat-value {
    font-size: 1.2em;
    font-weight: bold;
    color: #000;
}

.bottom-toolbar {
    position: fixed;
    width: calc(100% - 200px);
    bottom: 0;
    display: flex;
    justify-content: space-between;
    padding: 10px;
    background-color: #f5f5f5;
    border-top: 1px solid #ddd;
}

.bottom-toolbar button {
    padding: 5px 10px;
    background-color: #007bff;
    color: #fff;
    border: none;
    border-radius: 4px;
    cursor: pointer;
}

.no-questions-message {
    text-align: center;
    font-size: 1.5rem;
    color: #4CAF50;
    background-color: #f0f8f0;
    padding: 20px;
    border-radius: 10px;
    margin: 20px 0;
}

.no-questions-message p {
    margin: 0;
}

.selected {
    background-color: #FFA500 !important;
    color: white !important;
    border-radius: 5px;
}
</style>